import MenuApi from "@/api/menu";
import { defineStore } from "pinia";
import { ref } from "vue";

const modules = import.meta.glob("../../pages/**/**.vue"); //获取所有动态页面

import router, { constRoutes } from "@/router";

export const usePermissionStore = defineStore("permission", () => {

    const menus = ref([]);
    const roleRoutes = ref([]);

    function generateRoutes() {
        return MenuApi.loadMenus().then((list) => {
            roleRoutes.value = list
            menus.value = buildMenuTree(0, list);
            registRoutes(list)
            return list;
        });
    }

    function registRoutes(){ //重新注册全部路由
        console.log("roleRoutes", roleRoutes)
        let asyRoutes = [];
        let list = roleRoutes.value
        list.forEach((menu) => {
            let tmpRoute = parseRoute(menu);
            asyRoutes.push(tmpRoute);
        });
    
        let sysRoute = constRoutes.find((r) => r.path == "/");
        sysRoute.children = sysRoute.children.concat(asyRoutes);
        constRoutes.forEach((r) => {
            router.addRoute(r);
        });
        console.log("路由注册成功!", constRoutes)
    }
    return {menus, generateRoutes};
});



function parseRoute(menu) {
    const tmpRoute = { path: "", name: "", component: null, meta: null };
    if (menu.component == "Layout") {
        tmpRoute.component = () => import("../../pages/sys/Layout.vue");
    } else {
        const component = modules[`../../pages/${menu.component}.vue`];
        if (component) {
            tmpRoute.component = component;
        } else {
            tmpRoute.component = modules[`../../pages/error-page/404.vue`];
        }
    }
    if (menu.children) {
        tmpRoute.children = [];
    }
    tmpRoute.name = menu.routeName;
    tmpRoute.path = menu.routePath;
    tmpRoute.meta = { perm: menu.perm, id: menu.id };
    tmpRoute.menuName = menu.name;
    return tmpRoute;
}

function buildMenuTree(parentId, list) {
    let tree = list.filter(i=>i.parentId==parentId)
    .map(menu=>{
        let item = {...menu};
        item.children = buildMenuTree(item.id, list);
        return item;
    })
    return tree;
}
